package org.budo.sms.service.huawei;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.budo.support.fastjson.Fastjson;
import org.budo.support.http.client.Request;
import org.budo.support.http.client.Response;
import org.budo.support.lang.util.RandomUtil;
import org.budo.time.Time;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

/**
 * BudoHuaweiSmsServiceImpl
 * 
 * @author lmw
 */
@Getter
@Setter
@Slf4j
public class BudoHuaweiSmsServiceImpl implements BudoHuaweiSmsService {
    private static final String API_URL = "https://rtcsms.cn-north-1.myhuaweicloud.com:10743/sms/batchSendSms/v1";

    private String appKey;

    private String appSecret;

    private String from;

    @Override
    public String sendSms(String to, String template, Map<String, Object> parameters) {
        String nonce = RandomUtil.randomNumberString(5);
        String created = Time.now().toString("yyyy-MM-dd'T'HH:mm:ss'Z'");

        String sha256Hex = DigestUtils.sha256Hex(nonce + created + this.getAppSecret());
        String passwordDigest = Base64.encodeBase64String(sha256Hex.getBytes());

        String wsse = "UsernameToken Username=\"" + this.getAppKey() + "\", PasswordDigest=\"" + passwordDigest + "\", Nonce=\"" + nonce + "\", Created=\"" + created + "\"";

        Request request = new Request();
        request.setUrl(API_URL);
        request.setMethod(Request.POST);
        request.setHeader("Content-Type", "application/x-www-form-urlencoded");
        request.setHeader("Authorization", "WSSE realm=\"SDP\",profile=\"UsernameToken\",type=\"Appkey\"");
        request.setHeader("X-WSSE", wsse);

        request.setField("to", to);
        request.setField("templateId", template);

        request.setField("from", this.getFrom());

        List<String> paras = new ArrayList<String>();

        for (int i = 0;; i++) {
            Object val = null == parameters ? null : parameters.get(i + "");
            if (null == val) {
                break;
            }

            paras.add(val + "");
        }

        request.setField("templateParas", Fastjson.toJSONString(paras));

        Response response = request.execute();

        String responseBody = response.getBody();

        log.info("#27 response=" + response + ", request=" + request);
        return responseBody;
    }
}